#include "form_bedroom.h"
#include "ui_form_bedroom.h"

Form_bedroom::Form_bedroom(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_bedroom)
{
    ui->setupUi(this);
    qDebug() << "test->Bedroom";

    QPixmap img(":/new/prefix1/pictures/bedroom.jpeg");
    ui->label_img->setPixmap(img);

    connect(ui->pushButton_livingroom,SIGNAL(clicked()),this,SLOT(clickedLivingroomBtn()));
    connect(ui->pushButton_bedroom,SIGNAL(clicked()),this,SLOT(clickedBedroomBtn()));
    connect(ui->pushButton_scene,SIGNAL(clicked()),this,SLOT(clickedSceneBtn()));
    connect(ui->pushButton_set,SIGNAL(clicked()),this,SLOT(clickedSetBtn()));
    connect(ui->pushButton_noact,SIGNAL(clicked()),this,SLOT(clickedNoact()));
    connect(ui->pushButton_change,SIGNAL(clicked()),this,SLOT(clickedChange()));
    connect(ui->pushButton_time,SIGNAL(clicked()),this,SLOT(clickedTime()));
    //按钮设置颜色
    ui->pushButton_temperature->setIcon(QIcon(":/new/prefix1/pictures/温度计.png"));
    ui->pushButton_temperature->setIconSize(QSize(60,60));
    ui->pushButton_humidity->setIcon(QIcon(":/new/prefix1/pictures/湿度.png"));
    ui->pushButton_humidity->setIconSize(QSize(60,60));
    ui->pushButton_air_temp->setIcon(QIcon(":/new/prefix1/pictures/空调温度.png"));
    ui->pushButton_air_temp->setIconSize(QSize(60,60));
    ui->pushButton_light->setIcon(QIcon(":/new/prefix1/pictures/卧室灯.png"));
    ui->pushButton_light->setIconSize(QSize(60,60));
    ui->pushButton_lol->setIcon(QIcon(":/new/prefix1/pictures/英雄联盟.png"));
    ui->pushButton_lol->setIconSize(QSize(60,60));
    ui->pushButton_air_switch->setIcon(QIcon(":/new/prefix1/pictures/空调.png"));
    ui->pushButton_air_switch->setIconSize(QSize(60,60));
    //左侧按钮栏初始化
    ui->pushButton_livingroom->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_bedroom->setStyleSheet(QPushButton_STYTLE_ON);
    ui->pushButton_scene->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_set->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_noact->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_change->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_time->setStyleSheet(QPushButton_STYTLE_OFF);

    connect(ui->pushButton_temperature,SIGNAL(clicked()),this,SLOT(collectTemprature()));
    connect(ui->pushButton_humidity,SIGNAL(clicked()),this,SLOT(collectHumidity()));
    connect(ui->pushButton_air_temp,SIGNAL(clicked()),this,SLOT(collectAirTmeprature()));
    connect(ui->pushButton_light,SIGNAL(clicked()),this,SLOT(controlLight()));
    connect(ui->pushButton_air_switch,SIGNAL(clicked()),this,SLOT(controlAirSwitch()));
    connect(ui->pushButton_lol,SIGNAL(clicked()),this,SLOT(clickedBtnLOL()));

}
void Form_bedroom::connectServer()
{
    client = new QMQTT::Client(QHostAddress("192.168.31.161"),1883);
    client->setClientId("clientid");
    client->connectToHost();
    connect(client,SIGNAL(connected()),this,SLOT(doConnected()));
    connect(client,SIGNAL(subscribed(const QString&, const quint8)),this,SLOT(doSubscribed(const QString&, const quint8)));
    connect(client,SIGNAL(received(QMQTT::Message)),this,SLOT(doDataReceived(QMQTT::Message)));
}

void Form_bedroom::doConnected()//连接成功
{
    qDebug()<<"doConnected";
    client->subscribe("/app/data/up");//订阅"up"主题
}

void Form_bedroom::doSubscribed(const QString& topic, const quint8 qos)//订阅成功
{
    qDebug()<<"doSubscribed = "<<topic;
}

void Form_bedroom::doDataReceived(QMQTT::Message message)//接收数据
{
    QString mes = QString(message.id())+" "+QString(message.qos())+" "+message.topic()+" "+message.payload()+"\n";
    str = message.payload();
    qDebug()<<"mes="<<str;
    dataJsonDeserialization();
}

void Form_bedroom::dataJsonDeserialization()//数据查询Json反序列化
{
    QJsonParseError jsonError;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(str.toLatin1(),&jsonError));
    if(jsonError.error == QJsonParseError::NoError)
    {
        if(jsonDoc.isObject())
        {
            QJsonObject obj = jsonDoc.object();
            if(obj.contains("type"))
            {
                qDebug() << "type : " << obj["type"].toInt();
            }
            if(obj.contains("result"))
            {
                qDebug() << "result :" << obj["result"].toInt();
            }
            if(obj.contains("data"))
            {
                QJsonArray array = obj.value("data").toArray();
                for(int i = 0;i<array.size();i++)
                {
                    QJsonObject array_data = array.at(i).toObject();
                    qDebug() << "key : " << array_data.value("key").toInt();
                    qDebug() << "val : " << array_data.value("val").toInt();
                    if(array_data.contains("key"))
                    {
                        QJsonValue key_value = array_data.take("key");
                        if(key_value.isDouble())
                        {
                            key[i] = key_value.toVariant().toInt();
                        }
                    }
                    if(array_data.contains("val"))
                    {
                        QJsonValue value = array_data.take("val");
                        if(value.isString())
                        {
                            val[i] = value.toVariant().toString();
                        }
                    }
                }

            }
        }
    }
    else
    {
        qDebug() << "json error" << jsonError.errorString();
        return;
    }
    for(int j = 0;j<11;j++)
    {
        qDebug() << "QT解析出来的key值为:" << key[j] << "val值:" << val[j];
    }
}

void Form_bedroom::collectTemprature()//采集温度
{
    QMQTT::Message message;
    message.setTopic("/app/data/down");
    client->publish(message);
    qDebug()<<"doPulished = "<<message.topic();
    qDebug() << val[6];
    ui->label_tep->setText(val[6].append("℃"));
}

void Form_bedroom::collectHumidity()//采集湿度
{
    QMQTT::Message message;
    message.setTopic("/app/data/down");
    client->publish(message);
    qDebug()<<"doPulished = "<<message.topic();
    qDebug() << val[7];
    ui->label_hum->setText(val[7].append("%"));
}

void Form_bedroom::collectAirTmeprature()//采集空调温度
{
    QMQTT::Message message;
    message.setTopic("/app/data/down");
    client->publish(message);
    qDebug()<<"doPulished = "<<message.topic();
    qDebug() << val[8];
    ui->label_airtemp->setText(val[8].append("℃"));
}

void Form_bedroom::controlJsonDeserialization()//控制协议Json反序列化
{
    QJsonParseError jsonError;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(str.toLatin1(),&jsonError));
    if(jsonError.error == QJsonParseError::NoError)
    {
        if(jsonDoc.isObject())
        {
            QJsonObject obj = jsonDoc.object();
            if(obj.contains("type"))
            {
                qDebug() << "type : " << obj["type"].toInt();
            }
            if(obj.contains("result"))
            {
                qDebug() << "result :" << obj["result"].toInt();
            }
            if(obj.contains("msg"))
            {
                qDebug() << "msg : " << obj["msg"].toString();
            }
        }
    }
}

void Form_bedroom::controlLight()//控制卧室灯
{
    QJsonObject control_obj,item_obj;
    item_obj.insert("val",QString::number(num1%2));
    item_obj.insert("key",104);
    control_obj.insert("data",item_obj);
    control_obj.insert("type",2);
    QJsonDocument control_doc;
    control_doc.setObject(control_obj);
    QByteArray control_array = control_doc.toJson(QJsonDocument::Compact);
    QString control_str = control_array;

    QMQTT::Message message;
    message.setTopic("/app/control/down");
    message.setPayload(control_str.toLocal8Bit());
    client->publish(message);
    qDebug() << "doPublished = " << message.topic();
    qDebug() << control_str;
    if(num1%2 == 0)
    {
        ui->label_light->setText("  卧室灯|关");
    }
    else
    {
        ui->label_light->setText("  卧室灯|开");
    }
    num1++;
}

void Form_bedroom::controlAirSwitch()//控制空调开关
{
    QJsonObject control_obj,item_obj;
    item_obj.insert("val",QString::number(num1%2));
    item_obj.insert("key",104);
    control_obj.insert("data",item_obj);
    control_obj.insert("type",2);
    QJsonDocument control_doc;
    control_doc.setObject(control_obj);
    QByteArray control_array = control_doc.toJson(QJsonDocument::Compact);
    QString control_str = control_array;

    QMQTT::Message message;
    message.setTopic("/app/control/down");
    message.setPayload(control_str.toLocal8Bit());
    client->publish(message);
    qDebug() << "doPublished = " << message.topic();
    qDebug() << control_str;
    if(num2%2 == 0)
    {
        ui->label_airswitch->setText("  空调|关");
    }
    else
    {
        ui->label_airswitch->setText("  空调|开");
    }
    num2++;
}

QString Form_bedroom::modeJsonSerialization(int type_m)//模式修改Json序列化
{
    QString mode_str;
    QJsonObject mode_obj,item_obj;
    item_obj.insert("period",5);
    item_obj.insert("type",type_m);
    mode_obj.insert("data",item_obj);
    QJsonDocument mode_doc;
    mode_doc.setObject(mode_obj);
    QByteArray mode_array = mode_doc.toJson(QJsonDocument::Compact);
    mode_str = mode_array;
    return mode_str;
}

void Form_bedroom::modeJsonDeserialization()//模式修改Json反序列化
{
    QJsonParseError jsonError;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(str.toLatin1(),&jsonError));
    if(jsonError.error == QJsonParseError::NoError)
    {
        if(jsonDoc.isObject())
        {
            QJsonObject obj = jsonDoc.object();
            if(obj.contains("result"))
            {
                qDebug() << "result :" << obj["result"].toInt();
            }
            if(obj.contains("msg"))
            {
                qDebug() << "msg : " << obj["msg"].toString();
            }
        }
    }
}

//上报模式修改信号槽
void Form_bedroom::clickedNoact()
{
    ui->pushButton_noact->setStyleSheet(QPushButton_STYTLE_ON);
    ui->pushButton_change->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_time->setStyleSheet(QPushButton_STYTLE_OFF);

    QString mode_str(modeJsonSerialization(0));
    QMQTT::Message message;
    message.setTopic("/app/mode/down");
    message.setPayload(mode_str.toLocal8Bit());
    client->publish(message);
    qDebug() << "dePublished = " << message.topic();
    qDebug() << mode_str;
}

void Form_bedroom::clickedChange()
{
    ui->pushButton_noact->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_change->setStyleSheet(QPushButton_STYTLE_ON);
    ui->pushButton_time->setStyleSheet(QPushButton_STYTLE_OFF);

    QString mode_str(modeJsonSerialization(1));
    QMQTT::Message message;
    message.setTopic("/app/mode/down");
    message.setPayload(mode_str.toLocal8Bit());
    client->publish(message);
    qDebug() << "dePublished = " << message.topic();
    qDebug() << mode_str;
}

void Form_bedroom::clickedTime()
{
    ui->pushButton_noact->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_change->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_time->setStyleSheet(QPushButton_STYTLE_ON);

    QString mode_str(modeJsonSerialization(2));
    QMQTT::Message message;
    message.setTopic("/app/mode/down");
    message.setPayload(mode_str.toLocal8Bit());
    client->publish(message);
    qDebug() << "dePublished = " << message.topic();
    qDebug() << mode_str;
}

//界面切换四个槽函数
void Form_bedroom::clickedLivingroomBtn()
{
    ui->pushButton_livingroom->setStyleSheet(QPushButton_STYTLE_ON);
    ui->pushButton_bedroom->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_scene->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_set->setStyleSheet(QPushButton_STYTLE_OFF);

    Form_livingroom *lr = new Form_livingroom;
    lr->connectServer();
    this->hide();
    lr->show();
}

void Form_bedroom::clickedBedroomBtn()
{
    ui->pushButton_bedroom->setStyleSheet(QPushButton_STYTLE_ON);
    ui->pushButton_livingroom->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_scene->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_set->setStyleSheet(QPushButton_STYTLE_OFF);
}

void Form_bedroom::clickedSceneBtn()
{
    ui->pushButton_scene->setStyleSheet(QPushButton_STYTLE_ON);
    ui->pushButton_livingroom->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_bedroom->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_set->setStyleSheet(QPushButton_STYTLE_OFF);

    Form_scene *sce = new Form_scene;
    this->hide();
    sce->show();
}

void Form_bedroom::clickedSetBtn()
{
    ui->pushButton_set->setStyleSheet(QPushButton_STYTLE_ON);
    ui->pushButton_livingroom->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_bedroom->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_scene->setStyleSheet(QPushButton_STYTLE_OFF);

    Form_set *set = new Form_set;
    this->hide();
    set->show();
}

void Form_bedroom::clickedBtnLOL()
{
    Dialog_lol *lol = new Dialog_lol(this);
    lol->show();
}

Form_bedroom::~Form_bedroom()
{
    delete ui;
}

